package yzbx.personalwebsite.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import yzbx.personalwebsite.entity.HotTodayEntity;
import yzbx.personalwebsite.service.GetHotTodayService;
import yzbx.personalwebsite.tool.Httptool;
import yzbx.personalwebsite.tool.RedisTool;

import java.util.ArrayList;
import java.util.List;

/**
 * {@code @Author} zxm
 * {@code @Description} 获取微博热点数据服务类
 * {@code @Date} 2024/09/30/09:44
 * {@code @Version} 1.0
 */
@Service
public class GetHotTodayServiceWeibo extends GetHotTodayService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetHotTodayServiceWeibo.class);

    public GetHotTodayServiceWeibo(RedisTool redisTool, Httptool httptool) {
        super(redisTool, httptool);
    }

    @Override
    public List<HotTodayEntity> GetData(String logTheme) {
        List<HotTodayEntity> hotTodayList = new ArrayList<>();
        String url = "https://weibo.com/ajax/side/hotSearch";
        try {
            JSONObject jsonObject = httptool.doGet(url);
            JSONArray data = jsonObject.getJSONObject("data").getJSONArray("realtime");
            for (int i = 0; i < data.size() && hotTodayList.size() < DATA_NUM_MAX; i++) {
                JSONObject item = data.getJSONObject(i);
                if (item.get("word_scheme") == null) {
                    continue;
                }
                HotTodayEntity hotToday = new HotTodayEntity();
                hotToday.setIndex(hotTodayList.size() + 1 + "");
                hotToday.setTitle(item.get("word_scheme").toString().replace("#", ""));
                hotToday.setUrl("https://s.weibo.com/weibo?q=" + item.get("word_scheme").toString().replace("#", "%23"));
                hotTodayList.add(hotToday);
            }
            LOGGER.info("抓取{}数据成功，{}条", logTheme, hotTodayList.size());
        } catch (Exception e) {
            LOGGER.warn("抓取{}数据失败，失败信息：{}", logTheme, e.getMessage());
        }
        return hotTodayList;
    }

//    public static void main(String[] args) {
//        GetHotTodayServiceWeibo getHotTodayServiceWeibo = new GetHotTodayServiceWeibo(new RedisTool(), new Httptool());
//        getHotTodayServiceWeibo.GetData(THEME_WEIBO);
//
//    }
}
